package tech.aistar.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WebJavaRunner {
	
	private String in;
	private String classPath;
	private String name;
	private boolean isInput;
	private int timeout = 3000;

	public  List<String> executor() {
		String[] command = new String[] { "java", "-cp", classPath, name };
		ProcessBuilder build = new ProcessBuilder(command);
		if (isInput) {
			build.redirectInput(new File(in));
		}
		build.redirectErrorStream(true);
		Process p = null;
		try {
			p = build.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return readLinesByProcess(p);
	}
	
	private List<String>  readLinesByProcess(Process process){
		String line = null;
		BufferedReader br = null;
		Timer timer = new Timer();
		List<String> list = new ArrayList<String>();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				if(process.isAlive()) {
					process.destroy();
				}
			}
		}, timeout);
		try {
			br = new BufferedReader(
					new InputStreamReader(process.getInputStream(),"gbk"));
			while ((line = br.readLine()) != null) {
				list.add(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if( br != null ) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(process.isAlive()) {
					process.destroy();
				}
				timer.cancel();
			}
		}
		return list;
	}

	public String getIn() {
		return in;
	}
	public void setIn(String in) {
		this.in = in;
	}
	public String getClassPath() {
		return classPath;
	}
	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public boolean isInput() {
		return isInput;
	}

	public void setInput(boolean isInput) {
		this.isInput = isInput;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
	
	public interface RunnCaller{
		void onResult(List<String> result);
	}
}
